'use strict';
const requireEx=require('yi-require');
const lookup = require('yi-lookup');
const ObjectID = require('mongodb').ObjectID;

// const beforeSend = function (req,body,callback) {
//     let dataList = (body.data instanceof Array) ? body.data : body.data.items;
//     let lookupList = [];
//     lookupList.push({
//         from: "goods",
//         localField: "goodsId",
//         foreignField: "_id",
//         project:{lastModifyDate:0}
//     });
//     lookup.lookup(req.mongo, dataList, lookupList, (e, r) => {
//         callback(null, body);
//     });
// };
//
// const middleware =(req, res, next)=>{
//     req.beforeSend = beforeSend;
//     next();
// };

module.exports = {
    open:false,
//    middleware: middleware,
    description:'获取购物车商品',
//     handler: requireEx('yi-restful').r('cart')
   handler(req,res,next){
        let authInfo =  req.context||req.context.authInfo ;
        if(!req.context || !req.context.authInfo){
            return res.err.unauthorized();
        }
        authInfo = authInfo.authInfo;

        let userId = ObjectID(authInfo._id);

        let storeId = req.query.filter.storeId;

        req.mongo.collection("cart").aggregate([
            {
                $match: {userId:userId,storeId:storeId}
            },
            {
                $lookup:{
                    from:"goods",
                    localField:"goodsId",
                    foreignField:"_id",
                    as:"goods"
                }
            },
            {
                $unwind:"$goods"
            }
        ]).toArray((e0,r0)=>{
            if(e0) return res.err.mongoErrpr(e0);
            req.mongo.collection("store").findOne({_id:storeId},(e1,r1)=>{
                if(e1) return res.err.mongoError(e1);
                r1.goodsArr = r0;
                return res.reply({code:0,message:'查询成功',data:r1});
            });
        });
    }
};
